using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UIItem : MonoBehaviour
{
    public Image m_Preview;
    public Text m_NameL;
    ShipUI m_ShipUIPrefab;
    UIDesigner m_UIDesigner;
    public ShipUIPreviewer m_UIPreviewerMaskPrefab;

    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void Init(ShipUI shipUIPrefab, UIDesigner uiDesigner)
    {
        m_ShipUIPrefab = shipUIPrefab;
        m_NameL.text = m_ShipUIPrefab.GetTypeName();
        m_Preview.sprite = m_ShipUIPrefab.m_PreviewPrefab;
        m_UIDesigner = uiDesigner;
    }

    public void OnDragBegin(BaseEventData eventData)
    {
        var shipUI = Instantiate(m_ShipUIPrefab);
        shipUI.SetEditMode(true);
        shipUI.GetComponent<RectTransform>().anchorMin=new Vector2(0.5f, 0.5f);
        shipUI.GetComponent<RectTransform>().anchorMax=new Vector2(0.5f, 0.5f);

        var uiPreviewer = CreatePreviewer(shipUI);
        eventData.selectedObject = uiPreviewer.gameObject;

        shipUI.transform.SetParent(uiPreviewer.transform);
        shipUI.transform.SetSiblingIndex(0);
        shipUI.transform.localPosition = new Vector3(0,0,0);
        m_UIDesigner.SetPreviewersRaycastTarget(false);
    }
    public ShipUIPreviewer CreatePreviewer(ShipUI shipUI)
    {
        var uiPreviewer = Instantiate(m_UIPreviewerMaskPrefab);
        uiPreviewer.GetComponent<RectTransform>().sizeDelta = shipUI.GetComponent<RectTransform>().sizeDelta;
        var canvas = Utils.GetCanvas();
        uiPreviewer.transform.SetParent(canvas.transform);
        uiPreviewer.transform.SetSiblingIndex(canvas.transform.childCount - 1);
        uiPreviewer.SetRaycastTarget(false);
        uiPreviewer.Init(shipUI, m_UIDesigner);
        return uiPreviewer;
    }

    public void OnDragEnd(BaseEventData eventData)
    {
        Debug.Log("DragEnd");
        if (!eventData.selectedObject || (eventData.selectedObject.GetComponent<ShipUIPreviewer>() == null))
            return;
        m_UIDesigner.SetPreviewersRaycastTarget(true);
        eventData.selectedObject.GetComponent<ShipUIPreviewer>().SetRaycastTarget(true);
    }
    public void OnDraging(BaseEventData eventData)
    {
        if(eventData.selectedObject)
        {
            eventData.selectedObject.transform.position = Input.mousePosition;
        }
    }
    void jj()
    {

        //Vector2 mousePos = Input.mousePosition;
        //Vector2 vecMouse;
        //RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RectTransform>(), Input.mousePosition, null, out vecMouse);

        //vecMouse /= m_ImageScale;
        //return vecMouse;
    }
}
